#!/usr/bin/python
import subprocess
import sys

class Struct:
    """Struct/record-like class"""
    def __init__(self, **entries):
        self.__dict__.update(entries)

    def __repr__(self):
        args = ('%s=%s' % (k, repr(v)) for (k, v) in vars(self).iteritems())
        return 'Struct(%s)' % ', '.join(args)
    
    def __cmp__(self, other):
        if (vars(self) == vars(other)):
            return 0
        return 1    

def any(it, pred=bool):
    """Return True if any element in iterator matches the predicate."""
    for x in it:
        if pred(x):
            return True
    return False        

def all(it, pred=bool):
    """Return True if all elements in iterator matches the predicate."""
    for x in it:
        if not pred(x):
            return False
    return True

def debug(line, channel=sys.stderr):
    """Write line to standard error."""
    channel.write(str(line) + "\n")
    channel.flush()

def run(command, inputdata=None, **popen_kwargs):
    """Run a command with optional input."""
    kwargs = dict(stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    kwargs.update(popen_kwargs)
    popen = subprocess.Popen(command, **kwargs)
    data, errdata = popen.communicate(input=inputdata)
    if popen.returncode:
        debug("command failed: '%s'" % command)
    return popen.returncode, data, errdata
